// 文件名称：detail.js
// 完整保存路径：miniprogram/pages/communication/detail/detail.js
// 功能说明：医生交流详情页面逻辑控制
// 使用说明：处理咨询详情展示、医生回复查看等功能

const { getToken } = require('../../../utils/auth.js');

const app = getApp();

Page({
  data: {
    consultId: null,
    consult: null,
    loading: true,
    refreshing: false
  },

  onLoad(options) {
    console.log('医生交流详情页面加载');
    if (options.id) {
      this.setData({ consultId: parseInt(options.id) });
      this.loadConsultDetail();
    } else {
      wx.showToast({
        title: '缺少咨询ID',
        icon: 'error'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 2000);
    }
  },

  onPullDownRefresh() {
    this.refreshData();
  },

  /**
   * 加载咨询详情
   */
  async loadConsultDetail() {
    if (!this.data.consultId) return;
    
    try {
      this.setData({ loading: true });
      
      const token = getToken();
      if (!token) {
        wx.showToast({
          title: '请先登录',
          icon: 'error'
        });
        return;
      }
      
      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.apiBaseUrl}/communication/consults/${this.data.consultId}`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: resolve,
          fail: reject
        });
      });
      
      if (response.statusCode === 200 && response.data.success) {
        const { mapMediaUrls } = require('../../../utils/media');
        const raw = response.data.data;
        const normalized = {
          ...raw,
          images: mapMediaUrls(raw.images),
          reply_images: mapMediaUrls(raw.reply_images)
        };
        this.setData({
          consult: normalized,
          loading: false,
          refreshing: false
        });
        
        wx.stopPullDownRefresh();
      } else {
        throw new Error(response.data.message || '获取咨询详情失败');
      }
      
    } catch (error) {
      console.error('加载咨询详情失败:', error);
      this.setData({
        loading: false,
        refreshing: false
      });
      
      wx.stopPullDownRefresh();
      wx.showToast({
        title: error.message || '加载咨询详情失败',
        icon: 'error'
      });
    }
  },

  /**
   * 刷新数据
   */
  async refreshData() {
    this.setData({
      refreshing: true
    });
    
    await this.loadConsultDetail();
  },

  /**
   * 关闭咨询
   */
  async closeConsult() {
    const result = await new Promise((resolve) => {
      wx.showModal({
        title: '确认关闭',
        content: '关闭后将无法继续接收医生回复，确定要关闭这个咨询吗？',
        success: resolve
      });
    });
    
    if (!result.confirm) return;
    
    try {
      wx.showLoading({ title: '处理中...' });
      
      const token = getToken();
      if (!token) {
        wx.showToast({
          title: '请先登录',
          icon: 'error'
        });
        return;
      }
      
      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.apiBaseUrl}/communication/consults/${this.data.consultId}/close`,
          method: 'POST',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: resolve,
          fail: reject
        });
      });
      
      wx.hideLoading();
      
      if (response.statusCode === 200 && response.data.success) {
        wx.showToast({
          title: '咨询已关闭',
          icon: 'success'
        });
        
        // 刷新详情
        this.refreshData();
        
      } else {
        throw new Error(response.data.message || '关闭咨询失败');
      }
      
    } catch (error) {
      wx.hideLoading();
      console.error('关闭咨询失败:', error);
      wx.showToast({
        title: error.message || '关闭咨询失败',
        icon: 'error'
      });
    }
  },

  /**
   * 预览图片
   */
  previewImage(e) {
    const index = e.currentTarget.dataset.index;
    const type = e.currentTarget.dataset.type; // 'consult' or 'reply'
    
    let urls = [];
    if (type === 'consult') {
      urls = this.data.consult.images || [];
    } else if (type === 'reply') {
      urls = this.data.consult.reply_images || [];
    }
    
    if (urls.length > 0) {
      wx.previewImage({
        current: urls[index],
        urls: urls
      });
    }
  },

  /**
   * 复制文本内容
   */
  copyText(e) {
    const text = e.currentTarget.dataset.text;
    wx.setClipboardData({
      data: text,
      success: () => {
        wx.showToast({
          title: '内容已复制',
          icon: 'success'
        });
      }
    });
  },

  /**
   * 获取分类显示名称
   */
  getCategoryLabel(value) {
    const categories = {
      'vision_check': '视力检查',
      'intervention': '干预咨询',
      'symptoms': '症状询问',
      'treatment': '治疗方案',
      'prevention': '预防建议',
      'other': '其他问题'
    };
    return categories[value] || value;
  },

  /**
   * 获取优先级显示名称
   */
  getPriorityLabel(value) {
    const priorities = {
      'normal': '普通',
      'high': '高',
      'urgent': '紧急'
    };
    return priorities[value] || value;
  },

  /**
   * 获取状态显示名称
   */
  getStatusLabel(value) {
    const statuses = {
      'pending': '待回复',
      'replied': '已回复',
      'closed': '已关闭'
    };
    return statuses[value] || value;
  },

  /**
   * 返回上一页
   */
  navigateBack() {
    wx.navigateBack({
      delta: 1
    });
  },

  /**
   * 格式化时间
   */
  formatTime(timestamp) {
    if (!timestamp) return '';
    
    const date = new Date(timestamp);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  }
});
